//
//  NewRoomEditVController.m
//  YouinRTCDemo
//
//  Created by 潘欣 on 2024/6/16.
//

#import "NewRoomEditVController.h"
#import "TOCropViewController.h"
#import "UIButton+Extension.h"
@interface NewRoomEditVController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,TOCropViewControllerDelegate>
{
    int stream_url_type;
}
@property (nonatomic,strong)UIScrollView *scrollView;
@property (nonatomic,strong)UITextField *textName;
@property (nonatomic,strong)UITextField *textTime;
@property (nonatomic,strong)UITextField *wechatText;
@property (nonatomic,assign)BOOL isOpen;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, copy)NSString *imageUrl;
@property (nonatomic, copy)NSString *wechatImageUrl;
@property (nonatomic, strong) UIButton *coverImg;
@property (nonatomic, strong)UIButton *selectedButton;
@property (nonatomic, strong)UIButton *comformBtn1;
@property (nonatomic,assign)BOOL isLiveCover;//是不是直播的封面 1，0是微信分享缩略图
@property (nonatomic, strong)UIButton *wechatShareCover;
@end

@implementation NewRoomEditVController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
//    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
}
- (void)goBackToPreview{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    stream_url_type = 8;
    self.isLiveCover = YES;
    _isOpen = NO;
    self.title = @"新建直播";
    UIButton *buttonBack=[UIButton buttonWithType:UIButtonTypeCustom];
    buttonBack.frame =  CGRectMake(0, 0, 50, 50);
    [buttonBack setImage:[UIImage imageNamed:@"nav-return"] forState:UIControlStateNormal];
    [buttonBack addTarget:self action:@selector(goBackToPreview) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:buttonBack];
    buttonBack.imageEdgeInsets = UIEdgeInsetsMake(0, -27, 0, 0);
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.imageUrl = @"";
    self.wechatImageUrl = @"";
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RYColorForHex(@"#f5f6fa");
    
    self.scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:self.scrollView];
   
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    
    //直播名称
    UILabel *liveName = [[UILabel alloc] init];
    liveName.text = @"直播名称:";
    liveName.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveName.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:liveName];
//    [liveName setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];

    [liveName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.width.offset(70);
        make.top.mas_equalTo(self.scrollView).offset(15);
    }];
    
    
    self.textName = [[UITextField alloc] init];
    self.textName.placeholder = @"请输入直播名称";
    self.textName.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    self.textName.backgroundColor = [UIColor whiteColor];
    self.textName.layer.cornerRadius = 5;
    self.textName.clipsToBounds = YES;
    self.textName.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.textName.leftViewMode = UITextFieldViewModeAlways;
    [self.scrollView addSubview:self.textName];
    
    [self.textName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(liveName.mas_right).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.centerY.mas_equalTo(liveName);
        make.height.offset(35);
    }];
    
    
    //直播时间
    UILabel *liveTime = [[UILabel alloc] init];
    liveTime.text = @"直播时间:";
    liveTime.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveTime.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:liveTime];
    
    [liveTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(liveName.mas_bottom).offset(30);
    }];
    
    self.textTime = [[UITextField alloc] init];
    self.textTime.placeholder = @"请输入直播时间";
    self.textTime.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    self.textTime.backgroundColor = [UIColor whiteColor];
    self.textTime.layer.cornerRadius = 5;
    self.textTime.clipsToBounds = YES;
    self.textTime.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.textTime.leftViewMode = UITextFieldViewModeAlways;
    [self.scrollView addSubview:self.textTime];
    
    // 1. 创建时间格式化器
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    NSDate *currentDate = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:currentDate];

    NSLog(@"当前格式化时间: %@", currentTimeString);
    
    self.textTime.text = currentTimeString;
    
    
    [self.textTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(liveTime.mas_right).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.centerY.mas_equalTo(liveTime);
        make.height.offset(35);
    }];
    
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
   //设置地区: zh-中国
   datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
   datePicker.datePickerMode = UIDatePickerModeDateAndTime;
   [datePicker setDate:[NSDate date] animated:YES];
   //监听DataPicker的滚动
   [datePicker addTarget:self action:@selector(dateChange:) forControlEvents:UIControlEventValueChanged];
    self.datePicker = datePicker;
    self.textTime.inputView = datePicker;
    if(@available(iOS 13.4, *)) {
            self.datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
        }else{
            
        }
    
    //直播方式
    UILabel *liveWay = [[UILabel alloc] init];
    liveWay.text = @"直播方式:";
    liveWay.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveWay.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:liveWay];
    [liveWay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(self.textTime.mas_bottom).offset(20);
    }];
    
    
    UIButton *jisuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [jisuBtn setTitle:@"手机极速直播" forState:UIControlStateNormal];
    [jisuBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    jisuBtn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    [jisuBtn setImagePositionWithType:ImagePositionTypeLeft spacing:7];
    jisuBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [jisuBtn setImage:[UIImage imageNamed:@"notbingo_2x"] forState:UIControlStateNormal];
    [jisuBtn setImage:[UIImage imageNamed:@"bingo"] forState:UIControlStateSelected];
    [jisuBtn addTarget:self action:@selector(livesWayAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:jisuBtn];
    jisuBtn.tag = 200;
    
    [jisuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.textTime);
        make.centerY.mas_equalTo(liveWay);
        make.width.offset(150);
        
    }];
    
    UIButton *phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [phoneBtn setTitle:@"手机直播" forState:UIControlStateNormal];
    [phoneBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    phoneBtn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    [phoneBtn setImagePositionWithType:ImagePositionTypeLeft spacing:7];
    phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [phoneBtn setImage:[UIImage imageNamed:@"notbingo_2x"] forState:UIControlStateNormal];
    [phoneBtn setImage:[UIImage imageNamed:@"bingo"] forState:UIControlStateSelected];
    [phoneBtn addTarget:self action:@selector(livesWayAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:phoneBtn];
    phoneBtn.tag = 100;
    
    
    [phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
               
        make.left.mas_equalTo(jisuBtn.mas_right);
        make.centerY.mas_equalTo(liveWay);
        make.width.offset(100);
    }];
    
   
    
    if (self.isEdit) {
        //极速直播 = 8， 七牛直播 = 2
        if (self.model.stream_url_type == 8) {
            
            jisuBtn.selected = YES;
            self.selectedButton = jisuBtn;
        }else if(self.model.stream_url_type == 2){
            
            phoneBtn.selected = YES;
            self.selectedButton = phoneBtn;
        }
    }else{
        jisuBtn.selected = YES;
        self.selectedButton = jisuBtn;
    }
    
    //直播类型
    UILabel *liveMode = [[UILabel alloc] init];
    liveMode.text = @"直播类型:";
    liveMode.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveMode.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:liveMode];
    
    
    [liveMode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(liveWay.mas_bottom).offset(25);
    }];
    
    UIView *viewMode = [[UIView alloc] init];
    viewMode.layer.cornerRadius = 5;
    viewMode.clipsToBounds = YES;
    viewMode.layer.borderColor = RYColorForHex(@"#7fc4ff").CGColor;
    viewMode.layer.borderWidth = 1;
    viewMode.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:viewMode];
    
    [viewMode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.textName);
        make.top.mas_equalTo(liveWay.mas_bottom).offset(25);
        make.width.offset(114);
        make.height.offset(162);
    }];
    
    UIImageView *img = [[UIImageView alloc] init];
    img.image = [UIImage imageNamed:@"mode"];
    img.contentMode = UIViewContentModeScaleAspectFit;
    img.clipsToBounds = YES;
    [viewMode addSubview:img];
    [img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(viewMode).width.insets(UIEdgeInsetsMake(10, 10, 30, 10));
    }];
    
    //竖屏直播
    UILabel *livePortrait = [[UILabel alloc] init];
    livePortrait.text = @"竖屏直播";
    livePortrait.textAlignment = 1;
    livePortrait.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    livePortrait.textColor = RYColorForHex(@"#646566");
    [viewMode addSubview:livePortrait];
    
    [livePortrait mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(viewMode);
        make.top.mas_equalTo(img.mas_bottom).offset(6);
    }];
    
    //直播封面
    UILabel *liveCover = [[UILabel alloc] init];
    liveCover.text = @"直播封面:";
    liveCover.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveCover.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:liveCover];
    
    [liveCover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(viewMode.mas_bottom).offset(30);
    }];
    
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [coverBtn setImage:[UIImage imageNamed:@"youincoursecover1.jpeg"] forState:UIControlStateNormal];
    coverBtn.layer.cornerRadius = 5;
    coverBtn.clipsToBounds = YES;
    //允许裁剪图片
    coverBtn.imageView.clipsToBounds = YES;
    //设置具体的适配方式
    [coverBtn.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [coverBtn addTarget:self action:@selector(coverBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:coverBtn];
    [coverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.textName);
        make.top.mas_equalTo(liveCover);
        make.width.offset(116);
        make.height.offset(205);
    }];
    self.coverImg = coverBtn;
    
    
    //直播封面
    UILabel *liveTip = [[UILabel alloc] init];
    liveTip.text = @"支持JPG/JPEG/PNG格式,不超过2M, 建议尺寸720*1280像素";
    liveTip.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    liveTip.textColor = RYColorForHex(@"#646566");
    liveTip.numberOfLines = 2;
    [self.scrollView addSubview:liveTip];
    
    [liveTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(coverBtn.mas_left).offset(5);
        make.right.mas_equalTo(self.view).offset(-5);
        make.top.mas_equalTo(coverBtn.mas_bottom).offset(15);
    }];
    
    
    
    UILabel *wechatImage = [[UILabel alloc] init];
    wechatImage.text = @"微信分享缩略图:";
    wechatImage.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    wechatImage.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:wechatImage];
    
    [wechatImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(liveTip.mas_bottom).offset(30);
    }];
    
    UIButton *wechatShareImage = [UIButton buttonWithType:UIButtonTypeCustom];
    [wechatShareImage sd_setImageWithURL:[NSURL URLWithString:[YouinRTCManager shardManager].qiniu_user == 1?@"https://qncdn.youinsh.cn/saas_pro/image/qn_wx_logo.png": @"https://qncdn.youinsh.cn/saas_pro/image/youinwechatsharecard.png"] forState:UIControlStateNormal];
    wechatShareImage.layer.cornerRadius = 5;
    wechatShareImage.clipsToBounds = YES;
    wechatShareImage.imageView.clipsToBounds = YES;
    [wechatShareImage.imageView setContentMode:UIViewContentModeScaleAspectFill];
    [wechatShareImage addTarget:self action:@selector(wechatImageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:wechatShareImage];
    self.wechatShareCover = wechatShareImage;
    [wechatShareImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(wechatImage.mas_right).offset(10);
        make.top.mas_equalTo(wechatImage).offset(-10);
        make.width.offset(88);
        make.height.offset(88);
    }];
    
    UILabel *wechatTip = [[UILabel alloc] init];
    wechatTip.text = @"请上传2M以内的图片，支持JPG，PNG，JPEG格式。建议尺寸为200*200像素";
    wechatTip.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    wechatTip.textColor = RYColorForHex(@"#646566");
    wechatTip.numberOfLines = 3;
    [self.scrollView addSubview:wechatTip];
    
    [wechatTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(coverBtn.mas_left).offset(5);
        make.right.mas_equalTo(self.view).offset(-5);
        make.top.mas_equalTo(wechatShareImage.mas_bottom).offset(5);
    }];
    
    
    //直播封面
    UILabel *wechatLabel = [[UILabel alloc] init];
    wechatLabel.text = @"微信分享语:";
    wechatLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    wechatLabel.textColor = RYColorForHex(@"#646566");
    [self.scrollView addSubview:wechatLabel];
    
    [wechatLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(wechatTip.mas_bottom).offset(30);
    }];
    
    
    self.wechatText = [[UITextField alloc] init];
    self.wechatText.placeholder = @"请输入微信分享语";
    self.wechatText.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
//    self.wechatText.backgroundColor = [UIColor whiteColor];
    self.wechatText.layer.cornerRadius = 5;
    self.wechatText.clipsToBounds = YES;
    self.wechatText.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.wechatText.leftViewMode = UITextFieldViewModeAlways;
    [self.scrollView addSubview:self.wechatText];
    
    [self.wechatText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(wechatLabel.mas_right).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.centerY.mas_equalTo(wechatLabel);
        make.height.offset(35);
    }];
    
    if (self.isEdit&&![Tool strIsNULL:self.model.share_text]) {
        self.wechatText.text = self.model.share_text;
    }
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"在您的企业门户界面，显示本场直播." forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightRegular];
    [btn setImagePositionWithType:ImagePositionTypeLeft spacing:10];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btn setImage:[UIImage imageNamed:@"notbingo_2x"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"bingo"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(15);
        make.top.mas_equalTo(wechatLabel.mas_bottom).offset(30);
        make.right.mas_equalTo(self.view).offset(-15);
    }];

    //确定
    UIButton *comformBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    comformBtn.layer.cornerRadius = 20;
    comformBtn.clipsToBounds = YES;
    comformBtn.backgroundColor = [UIColor systemBlueColor];
    [comformBtn setTitle:@"立即创建" forState:UIControlStateNormal];
    [comformBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    comformBtn.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
    [comformBtn addTarget:self action:@selector(comformAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:comformBtn];
    
    [comformBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.scrollView).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.top.mas_equalTo(btn.mas_bottom).offset(15);
        make.height.offset(40);
    }];

    
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(comformBtn).offset(100);
        make.left.right.mas_equalTo(self.view);
    }];
    
    
    
    if (self.isEdit) {
        self.textName.text = self.model.title;
        
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
        NSDate *date = [formatter dateFromString:self.model.start_time];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *formattedDateString = [formatter stringFromDate:date];
        self.textTime.text = formattedDateString;
        
        [self.coverImg sd_setImageWithURL:[NSURL URLWithString:self.model.image] forState:UIControlStateNormal];
        [self.wechatShareCover sd_setImageWithURL:[NSURL URLWithString:self.model.third_image] forState:UIControlStateNormal];
        [comformBtn setTitle:@"修改" forState:UIControlStateNormal];
        btn.selected = self.model.isOpen;
        self.imageUrl = self.model.image;
        self.wechatImageUrl = self.model.third_image;
    }
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    // 只在布局改变时更新 contentSize
//        [self updateScrollViewConstraints];
}

//- (void)updateScrollViewContentSize {
//    CGFloat comformBtnY = self.comformBtn1.frame.origin.y;
//    CGSize newSize = CGSizeMake(SCREEN_WIDTH, 50 + comformBtnY);
//    
//    // 使用条件判断以避免不必要的更新
//    if (!CGSizeEqualToSize(self.scrollView.contentSize, newSize)) {
//        self.scrollView.contentSize = newSize;
//    }
//}
//禁止用户输入文字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.textTime) {
        return NO;
    }
    return YES;
}

- (void)dateChange:(UIDatePicker *)datePicker {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //设置时间格式
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSString *dateStr = [formatter  stringFromDate:datePicker.date];
    
    self.textTime.text = dateStr;
}
#pragma mark -  更换封面图
- (void)coverBtnAction:(UIButton *)sender
{
    self.isLiveCover = YES;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NULL message:NULL preferredStyle:UIAlertControllerStyleActionSheet];
     
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        [self takePhoto];
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [self imageBtnClick];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
         
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
    
}


- (void)wechatImageBtnAction:(UIButton *)sender
{
    self.isLiveCover = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NULL message:NULL preferredStyle:UIAlertControllerStyleActionSheet];
     
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        [self takePhoto];
        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [self imageBtnClick];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
         
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)livesWayAction:(UIButton *)sender
{
    self.selectedButton.selected = NO;
    sender.selected = YES;
    self.selectedButton = sender;
    if (sender.tag == 100) {
        stream_url_type = 2;
    }else{
        stream_url_type = 8;
    }
}

#pragma mark - 选择是否更新到企业门户
- (void)btnAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    _isOpen = sender.selected;
}

// 输入: "2025-05-12 3:01 PM" 或 "2025-05-12 1:01 AM"
// 输出: "2025-05-12T15:01:00" 或 "2025-05-12T01:01:00"
- (NSString *)convertToBackendFormat:(NSString *)displayTime {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    inputFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CNh"]; // 固定区域
    inputFormatter.dateFormat = @"yyyy-MM-dd ah:mm"; // 注意: "h"是12小时制, "a"是AM/PM
    
    NSDate *date = [inputFormatter dateFromString:displayTime];
    if (!date) return nil;
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    outputFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CNh"];
    outputFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss"; // ISO 8601
    
    return [outputFormatter stringFromDate:date];
}

#pragma mark - 确认创建
- (void)comformAction:(UIButton *)sender
{
    if ([self strIsNULL:self.textName.text]) {
        [[ZXMessageCase shareInstace] showMessage:@"请输入直播名称"];
        return;
    }
    if ([self strIsNULL:self.textTime.text]) {
        [[ZXMessageCase shareInstace] showMessage:@"请选择直播时间"];
        return;
    }
    
    
    self.textTime.text = [Tool is24HourFormat]?self.textTime.text:[self convertToBackendFormat:self.textTime.text];
    
    NSString *url = @"";
    
    NSString *shareUrl = @"";
    NSDictionary *dict;
    if (![self strIsNULL:self.imageUrl]) {
        url = self.imageUrl;
    }else{
        url = @"https://qncdn.youinsh.cn/saas_pro/image/youincoursecover1.jpeg";
        
    }
    
    if (![self strIsNULL:self.wechatImageUrl]) {
        shareUrl = self.wechatImageUrl;
    }else{
        shareUrl = [YouinRTCManager shardManager].qiniu_user == 1?@"https://qncdn.youinsh.cn/saas_pro/image/qn_wx_logo.png": @"https://qncdn.youinsh.cn/saas_pro/image/youinwechatsharecard.png";
    }
    
    sender.enabled = NO;
    if (self.isEdit) {//只有管理员和子账号身份可以修改
                    
        dict = @{@"image":url,
                @"isOpen":@(_isOpen),
                @"play_mode":@1,
                @"start_time":self.textTime.text,
                @"stream_url_type":@(stream_url_type),
                @"title":self.textName.text,
                @"liveId":self.model.ID,
                 @"third_image":shareUrl,//微信分享图
                @"share_text":[Tool strIsNULL:self.wechatText.text]?@"":self.wechatText.text,//微信分享语
        };
        
       [[YouinRTCManager shardManager] getModifyCourse:dict successBlock:^(id  _Nonnull json) {
           sender.enabled = YES;
           if ([json[@"code"] intValue] == 200) {
               if ([self.delegate respondsToSelector:@selector(toCheckIsSuccessCreateCourse:)]) {
                   [self.delegate toCheckIsSuccessCreateCourse:YES];
               }
               [self.navigationController popViewControllerAnimated:YES];
           }else{
               
               [[ZXMessageCase shareInstace] showMessage:json[@"msg"]];
           }
           
       } failure:^(NSError * _Nonnull error) {
           
       }];
        
    }else{
        
        dict = @{@"image":url,
                    @"isOpen":@(_isOpen),
                    @"play_mode":@1,
                    @"start_time":self.textTime.text,
                    @"stream_url_type":@(stream_url_type),
                    @"title":self.textName.text,
                    @"third_image":shareUrl,//微信分享图
                    @"share_text":[Tool strIsNULL:self.wechatText.text]?@"":self.wechatText.text,
        };
        
        [[YouinRTCManager shardManager] getCreateCourse:dict successBlock:^(id  _Nonnull json) {
            
            sender.enabled = YES;
            if ([json[@"code"] intValue] == 200) {
                if ([self.delegate respondsToSelector:@selector(toCheckIsSuccessCreateCourse:)]) {
                    [self.delegate toCheckIsSuccessCreateCourse:YES];
                }
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [[ZXMessageCase shareInstace] showMessage:json[@"msg"]];
            }
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
        
    }
}

-(BOOL)strIsNULL:(NSString *)str
{
    if ([str isEqualToString:@""]||str.length==0||[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length]==0||[str isEqualToString:@"0"] || [str isEqualToString:@"00"]) {
        return YES;
    }else{
        return NO;
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
}

//开始拍照
-(void)takePhoto{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        picker.modalPresentationStyle = UIModalPresentationCurrentContext;
        picker.sourceType = sourceType;
        picker.modalPresentationStyle = UIModalPresentationFullScreen;
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }else{
        
    }
}

-(void)imageBtnClick{
    UIImagePickerController *photo = [[UIImagePickerController alloc] init];
    photo.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    photo.delegate = self;
    photo.allowsEditing = NO;
    photo.view.backgroundColor=[UIColor whiteColor];
    photo.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:photo animated:YES completion:nil];
}
//当选择一张图片进入
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *smallimage;
    if (picker.allowsEditing == YES) {
        smallimage  = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    }else{
        smallimage  = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    }
    
    TOCropViewController *cropViewController = [[TOCropViewController alloc] initWithImage:smallimage];
    cropViewController.delegate = self;
    cropViewController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetCustom;
    cropViewController.toolbar.rotateClockwiseButtonHidden = YES;
    cropViewController.toolbar.clampButtonHidden = YES;
    cropViewController.toolbar.rotateCounterclockwiseButtonHidden = YES;
    cropViewController.toolbar.resetButtonHidden = YES;
    cropViewController.aspectRatioLockEnabled = YES;
    cropViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:cropViewController animated:NO completion:nil];
}

- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle
{
    __weak typeof(self) weakSelf = self;
    if (self.isLiveCover) {
        [[YouinRTCManager shardManager] getUploadFile:image successBlock:^(id  _Nonnull json) {
            
            if ([json[@"code"] intValue] == 200) {
                weakSelf.imageUrl = json[@"result"][@"file_url"];
                [weakSelf.coverImg sd_setImageWithURL:[NSURL URLWithString:weakSelf.imageUrl] forState:UIControlStateNormal];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }else
    {
        [[YouinRTCManager shardManager] uploadFileToQiniu:image successBlock:^(id  _Nonnull json) {
            NSLog(@"json");
            if ([json[@"code"] intValue] == 200) {
                weakSelf.wechatImageUrl = json[@"result"][@"file_url"];
                [weakSelf.wechatShareCover sd_setImageWithURL:[NSURL URLWithString:weakSelf.wechatImageUrl] forState:UIControlStateNormal];
            }
        } failure:^(NSError * _Nonnull error) {
            NSLog(@"error");
        }];
    }

    [cropViewController dismissViewControllerAnimated:NO completion:nil];
}
@end
